package com.hnly.djdl

import android.content.Intent
import android.os.Bundle
import android.os.Process
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.Divider
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import androidx.core.view.WindowCompat
import androidx.lifecycle.lifecycleScope
import com.hnly.djdl.global.requestTag
import com.normal.utils.AppInfo
import com.hnly.djdl.model.HUrl
import com.hnly.djdl.components.CenterTextDialog
import com.hnly.djdl.components.WebViewDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class SplashActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        WindowCompat.setDecorFitsSystemWindows(window, false)
        lifecycleScope.launch(Dispatchers.IO) {
            requestTag("Splash-isAgree=${AppInfo.isAgree}")
        }
        if (AppInfo.isAgree) {
            startActivity(Intent(applicationContext, MarketNewActivity::class.java))
            finish()
        }
        setContent {
            SplashApp(clickAgree = { agree ->
                if (agree) {
                    AppInfo.isAgree = true
                    // 跳转到下一个
                    startActivity(Intent(applicationContext, MarketNewActivity::class.java))
                    finish()
                } else {
                    Process.killProcess(Process.myPid());
                }
            })
        }
    }
}

@Composable
fun SplashApp(clickAgree: (Boolean) -> Unit) {
    val showAgreeDialog = remember { mutableStateOf(false) }
    val showAgreementDialog = remember { mutableStateOf(false) }
    val showPrivacyDialog = remember { mutableStateOf(false) }
    LaunchedEffect(key1 = Unit) {
        if (!AppInfo.isAgree) {
            delay(1000)
            showAgreeDialog.value = true
        }
    }
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        Image(
            painter = painterResource(id = R.mipmap.ic_launcher),
            contentDescription = null,
            modifier = Modifier
                .size(150.dp)
                .align(Alignment.Center)
        )
    }
    if (showAgreeDialog.value) {
        TipsDialog(
            onAgree = { agree ->
                clickAgree(agree)
                showAgreeDialog.value = false
            },
            onAgreement = { showAgreementDialog.value = true },
            onPrivacy = { showPrivacyDialog.value = true }
        )
    }
    if (showAgreementDialog.value) {
        WebViewDialog(url = HUrl.agreement()) {
            showAgreementDialog.value = false
        }
    }
    if (showPrivacyDialog.value) {
        WebViewDialog(url = HUrl.privacy()) {
            showPrivacyDialog.value = false
        }
    }
}


@Composable
private fun TipsDialog(onAgree: (Boolean) -> Unit, onAgreement: () -> Unit, onPrivacy: () -> Unit) {
    val appName = stringResource(id = R.string.app_name) // ${AppUtils.getAppName(LocalContext.current)}
    val text = """
    亲爱的用户，欢迎你信任并使用${appName}，我们依据相关法律制定了《用户协议》和《隐私政策》帮助你了解我们收集、使用、储存和共享个人信息的情况，请你在点击之前仔细阅读并充分理解相关条款，其中重点条款已为你标注，方便你了解自己的相关权利，我们将通过《隐私政策》向你说明：
    1. 你在使用我们产品或服务时，将会提供与具体功能相关的个人信息（可能涉及地理位置、读取通讯录、运动记录、位置信息等），如您不希望开启相关功能，可停止使用对应服务，我们将不会开启与用户使用的服务无关的功能。
    2. 当我们要将信息用于本策略未载明的其他用途时，会事先征求您的同意。 您在使用我们产品时，我们会在您的同意之后会获取软件安装列表用以反作弊处理，获取Mac地址、DeviceId、IMEI、IMSI、AndroidId等设备信息用于唯一标识唯一设备与反作弊处理。
    3. 此外我们还会请求用户地理位置信息（可选，不会收集精确位置信息）用于广告个性化推荐与用户统计，如您不希望开启相关功能，可停止使用对应服务，我们将不会开启与用户使用的服务无关的功能。
    4. 我们会每天只收集一次手机应用安装列表，获取本公司其他产品的包名，目的是方便验证您是否完成您在本应用的每日福利任务，便于您更快捷的完成每日任务，使您有更好的体验。
    5. 当我们要将基于特定目的收集而来的信息用于其他目的时，会事先征求您的同意。您在注册软件账户或使用服务的过程中，向我们提供的相关个人信息，例如真实姓名、手机号码、电子邮件、IP地址（以下称个人信息）等，我们将采取必要措施保护您的个人信息安全。
    6. 未经您的同意，我们不会将您的个人信息共享给第三方。
    """.trimIndent()
    CenterTextDialog(
        title = "温馨提示",
        height = 400.dp,
        properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false),
        onDismissRequest = { },
    ) {
        HorizontalDivider()
        LazyColumn(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .padding(start = 10.dp, end = 10.dp, top = 10.dp)
        ) {
            item { Text(text = text) }
        }
        HorizontalDivider()
        SpannableAgreementPrivacyText(onAgreement, onPrivacy)
        HorizontalDivider()
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(68.dp)
        ) {
            TextButton(
                onClick = { onAgree(true) }, modifier = Modifier
                    .fillMaxHeight()
                    .weight(1f)
            ) {
                Text(text = "同意", style = TextStyle.Default.copy(fontSize = 20.sp))
            }
            Divider(
                modifier = Modifier
                    .padding(vertical = 5.dp)
                    .fillMaxHeight()
                    .width(1.dp)
            )
            TextButton(
                onClick = { onAgree(false) }, modifier = Modifier
                    .fillMaxHeight()
                    .weight(1f)
            ) {
                Text(text = "不同意", style = TextStyle.Default.copy(fontSize = 20.sp))
            }
        }
    }
}

@Composable
private fun SpannableAgreementPrivacyText(onAgreement: () -> Unit, onPrivacy: () -> Unit) {
    val style = SpanStyle(Color.Red, fontWeight = FontWeight.Bold)
    // 《用户协议》和《隐私政策》
    val annotatedString = buildAnnotatedString {
        append("你可以通过阅读完整版")

        pushStringAnnotation(tag = "agreement", annotation = "agreement")
        withStyle(style = style) {
            append("《用户协议》")
        }
        pop()

        append(" 和 ")

        pushStringAnnotation(tag = "privacy", annotation = "privacy")
        withStyle(style = style) {
            append("《隐私政策》")
        }
        pop()

        append("了解详细信息。如你同意，请点击“同意”开始接受我们的服务")
    }
    ClickableText(text = annotatedString, modifier = Modifier.padding(10.dp)) { offset ->
        if (BuildConfig.DEBUG) {
            Log.i("SpannableAgreement", "offset -> $offset")
        }
        annotatedString.getStringAnnotations(tag = "agreement", start = offset, end = offset)
            .firstOrNull()?.let {
                onAgreement()
            }
        annotatedString.getStringAnnotations(tag = "privacy", start = offset, end = offset)
            .firstOrNull()?.let {
                onPrivacy()
            }
    }
    //BasicText(text = annotatedString)
}

@Composable
private fun HorizontalDivider() {
    Divider(
        modifier = Modifier
            .fillMaxWidth()
            .height(1.dp)
    )
}

@Preview
@Composable
private fun TipsDialogPreview() {
    TipsDialog(
        {},{},{}
    )
}

@Preview
@Composable
fun SplashAppPreview() {
    SplashApp(
        clickAgree = {},

    )
}